<?php

class GateWay {

    public static function CheckLogin() {

        if (!isset($_SESSION['id']) && !isset($_REQUEST['id']))
            return false;
        return true;
    }

    public static function Login() {

        list($userid, $hash) = getParams('id', 'hash');

        if (SERVER == 'localhost') {
            $hash = "none";
        }
        if (!$userid || !$hash) {
            return false;
        }

        $_SESSION['id'] = $userid;
        $_SESSION['secret'] = md5(uniqid());

        $db = DBUtils::Create();
        $res = $db->getUser($userid, $hash);

        if ($res) {
            $gid = getRoomId();
            if ($gid > 0)
                return "ingame";
            $lobby = loadLobby();
            $lobby->AddUser($userid);
            return "lobby";
        }
        return $res;
    }

    public static function addUser() {

        list($userid, $userHash, $userGender, $adminHash) = getParams('id', 'userHash', 'gender', 'adminHash');

        if (!$userid || !$userHash || !$adminHash) {
            return false;
        }

        if (!$userGender)
            $userGender = 'male';

        $db = DBUtils::Create();
        $res = $db->findUser('Admin', $adminHash);
        if (!$res)
            return false;

        $db->createUser($userid, $userGender, $userHash);
        return true;
    }

    public static function changePass() {
        list($userid, $oldPass, $newPass) = getParams('id', 'oldPass', 'newPass');
        $db = DBUtils::Create();
        $res = $db->getUser($userid, $oldPass);

        if (!$res) {
            return false;
        }

        $res = $db->setPass($userid, $newPass);
        return $res;
    }

    public static function undo() {
        $userid = $_SESSION['id'];
        $gid = getRoomId();
        if ($gid > 0) {
            $game = loadgame();
            $game->undo($userid);
            $game->save();
            $game->setUniqueID($userid);
        } else {
            
        }
    }

    public static function addChatLine() {

        checkParams('line');
        list($line) = getParams('line');
        $line = urldecode($line);
        
        $userid = $_SESSION['id'];

        $gid = getRoomId();
        if ($gid > 0) {
            $game = loadgame();
            Chat::addLine($game, $userid, $line);
        } else {
            $lobby = loadlobby();
            Chat::addLine($lobby, $userid, $line);
        }
    }

    public static function Lobby() {
        $lobby = loadLobby();
        $userid = getUserId();
        $lobby->addUser($userid);
        $data = DataManager::inLobbyData($lobby);
        return $data;
    }

    public static function LoadGame() {
        checkParams('roomid');
        list($roomid) = getParams('roomid');
        $userid = getUserId();
    }

    public static function getRoomCardsData() {
        checkPermissions();
        $gid = getRoomId();
        $room = null;
        if ($gid > 0) {
            $room = loadGame();
        } else {
            $room = loadLobby();
        }
        $data = DataManager::getRoomCardsData($room);

        return $data;
    }

    public static function Action() {
        checkPermissions();
        checkParams('card');
        list($card) = getParams('card');
        $game = loadGame();
        $game->action($card);
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function Payment() {
        checkPermissions();
        checkParams('card');
        list($card) = getParams('card');
        $game = loadGame();
        $game->payment($card);
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function Buy() {
        //checkPermissions();
        checkParams('card');
        list($card) = getParams('card');
        $game = loadGame();
        $game->buy($card);
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function Input() {

        $output_params = "";
        $i = 0;
        //getting the first card
        list($p) = getParams("$i");

        while ($p != null) {
            if ($p != 'off') {
                //saving the option
                $output_params .= $p . "|";
            }
            $i+=1;
            //getting the other cards in order
            list($p) = getParams("$i");
        }

        $name = getUserId();

        $roomid = getRoomId();
        $room = loadGame();
        $phase = $room->getPhase();

        //if this is the input for black market, we want to call a buy method of black market.
        //this is not a usual socket issue - it is more like regular payment - buy architecture
        if ($phase == Phase_BlackMarketPayment) {
            $bm = new BlackMarket();
            $res = preg_split('/\|/', $output_params, -1, PREG_SPLIT_NO_EMPTY);
            $bm->buyCard($room, $res[0]);
            $room->save();
        } elseif ($phase == Phase_DigitalStorePayment) {
            $ds = new DigitalStore();
            $res = preg_split('/\|/', $output_params, -1, PREG_SPLIT_NO_EMPTY);
            $ds->buyCard($room, $res[0]);
            $room->save();
        }
        //in all other cases, we use the socket api
        else {
            MySocket::setUserOutput($roomid, $name, $output_params);
        }
        if ($roomid > 0) {
            $data = DataManager::inGameData($room);
        } else {
            $data = DataManager::inLobbyData($room);
        }

        //return $data;
    }

    public static function BuyPhaseAndPlayAllTreasures() {
        //checkPermissions();
        $game = loadGame();
        $game->buyPhaseAndPlayAllTreasures();
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }
    
    public static function playCoinTokens() {
        //checkPermissions();
        $game = loadGame();
        $game->playCoinTokens();
        $game->save();
        $data = DataManager::inGameData($game);
    }

    public static function BuyPhase() {
        //checkPermissions();
        $game = loadGame();
        $game->buyPhase();
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function StartGame() {
        $lobby = loadLobby();
        $game = $lobby->startGame();
        $res = $game->save();
        $lobby->save();
    }

    public static function EndTurn() {
        //checkPermissions();
        $game = loadGame();
        $game->endTurn();
        $game->save();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function ExitGame() {
        //checkPermissions();
        $game = loadGame();
        $lobby = loadLobby();
        $userid = getUserId();
        $isGameOver = $game->isGameOver();
        if ($isGameOver) {
            $game->gameOver($userid);
        } else {
            $game->gameResign($userid);
        }

        $lobby->AddUser($userid);
        //setRoom($lobby, $userid);
        //$lobby->setPhase(Phase_Available, $userid);
    }

    public static function Logout() {
        //checkPermissions();

        $userid = getUserId();
        $lobby = loadLobby();
        $lobby->RemoveUser($userid);
        //$lobby->setPhase(Phase_Disconnected, $lobby->getCurrentPlayerName($userid));

        $db = DBUtils::Create();
        $rooms = $db->getAllRoomsForPlayer($userid);
        $db->deleteInputOutput($lobby->getID(), $userid);
        foreach ($rooms as $rid) {
            // unset room id might be needed.
            $db->removeFromRoom($rid[0], $userid);
        }

        unset($_SESSION['id']);
        unset($_SESSION['secret']);
    }

    public static function getGameData() {
        $game = loadGame();
        $data = DataManager::inGameData($game);
        //return $data;
    }

    public static function invite() {
        $lobby = loadLobby();
        $game = $lobby->invite();
        $lobby->save();
        
        if ($game) {
            $game->save();
            $data['redirect'] = "ingame.html";
        } else {
            $data = DataManager::inLobbyData($lobby);
        }
        return $data;
    }

    public static function checkForChatUpdates() {
        checkParams('last_chat_id');
        list($last_chat_line_id) = getParams('last_chat_id');

        $gid = getRoomId();
        $room = null;
        if ($gid > 0)
            $room = loadGame();
        else
            $room = loadLobby();

        $all_chat_line_ids = DataManager::getChatLinesIDs($room);
        $current_chat_line_id = array_pop($all_chat_line_ids);
        set_time_limit(120);
        $counter = 0;
        while (($current_chat_line_id == null || $current_chat_line_id == $last_chat_line_id ) && $counter < 60) {
            $counter++;

            session_write_close();
            usleep(500000);
            session_start();

            $all_chat_line_ids = DataManager::getChatLinesIDs($room);
            $current_chat_line_id = array_pop($all_chat_line_ids);
        }
        if ($current_chat_line_id && ($current_chat_line_id != $last_chat_line_id)) {
            //var_dump($last_chat_line_id);
            //var_dump($current_chat_line_id);
            //die;
            $gid = getRoomId();
            if ($gid > 0) {
                $game = loadGame();
                $data = DataManager::chat($game);
                $data['modifications'] = true;
                $data['current'] = $current_chat_line_id;
                $data['last'] = $last_chat_line_id;
            } else {
                $game = loadLobby();
                $data = DataManager::chat($game);
                $data['modifications'] = true;
                $data['current'] = $current_chat_line_id;
                $data['last'] = $last_chat_line_id;
            }
        } else {
            $data = array('modifications' => false);
        }
        return $data;
    }

    public static function checkModifications() {
        checkParams('current_uniqueid');
        list($current_uniqueid) = getParams('current_uniqueid');

        $userid = getUserId();

        $db = DBUtils::Create();
        $db->updateLastUpdateTime($userid);
        $old_room = getRoomId();
        if ($old_room == 0) {
            $someone_deleted = $db->clearLobby(0);
            if ($someone_deleted)
                $db->setUniqueid($userid);
        }


        $all_chat_line_ids = DataManager::GetUniqueID($userid);

        $old_room = getRoomId();
        $old_phase = $db->getPhase($userid);
        /*
          if (!$old_phase) {
          GateWay::Login();
          $old_phase = $db->getPhase($userid);
          // $data = array('modifications' => false);
          // return $data;
          }
         */
        //long pooling
        set_time_limit(120);
        $counter = 0;
        while ($all_chat_line_ids == $current_uniqueid && $counter < 60) {
            $counter++;

            session_write_close();
            usleep(500000);
            session_start();

            $all_chat_line_ids = DataManager::GetUniqueID($userid);
        }

        $new_phase = $db->getPhase($userid);
        #new phase is sleep, give a chance to game to set a new phase and prevent trip and jumps
        if ($all_chat_line_ids != $current_uniqueid && ($new_phase == Phase_Sleep || $new_phase == Phase_Output)) {

            for ($counter = 0; $counter < 10; $counter++) {

                session_write_close();
                usleep(100000);
                session_start();

                $new_phase = $db->getPhase($userid);
                if ($new_phase != Phase_Sleep && $new_phase != Phase_Output) {
                    break;
                }
            }
        }

        $new_room = getRoomId();

        if ($new_room != $old_room) {
            $data = array();
            if ($new_room == 0) {
                $data['redirect'] = "lobby.html";
            } else {
                $data['redirect'] = "ingame.html";
            }
        } else if ($all_chat_line_ids != $current_uniqueid) {
            $gid = getRoomId();
            if ($gid > 0) {
                $game = loadGame();
                $data = DataManager::inGameData($game);
            } else {
                $lobby = loadlobby();
                $data = DataManager::inLobbyData($lobby);
            }
            $data['modifications'] = true;
        } else {
            $data = array('modifications' => false);
        }
        return $data;
    }

}

?>